package com.hqd.ch03.v40.web.servlet.support;

import com.hqd.ch03.v40.core.Ordered;
import com.hqd.ch03.v40.utils.StringUtils;
import com.hqd.ch03.v40.web.HttpRequestMethodNotSupportedException;
import com.hqd.ch03.v40.web.servlet.AbstractHandlerExceptionResolver;
import com.hqd.ch03.v40.web.servlet.ModelAndView;
import com.hqd.ch03.v40.web.servlet.NoHandlerFoundException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 默认异常处理器
 */
public class DefaultHandlerExceptionResolver extends AbstractHandlerExceptionResolver {

    public DefaultHandlerExceptionResolver() {
        setOrder(Ordered.LOWEST_PRECEDENCE);
    }

    @Override
    protected ModelAndView doResolveException(
            HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {

        try {
            if (ex instanceof HttpRequestMethodNotSupportedException) {
                return handleHttpRequestMethodNotSupported(
                        (HttpRequestMethodNotSupportedException) ex, request, response, handler);
            } else if (ex instanceof NoHandlerFoundException) {
                return handleNoHandlerFoundException(
                        (NoHandlerFoundException) ex, request, response, handler);
            }
        } catch (Exception handlerEx) {
            handlerEx.printStackTrace();
        }
        return null;
    }

    protected ModelAndView handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException ex,
                                                               HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {

        String[] supportedMethods = ex.getSupportedMethods();
        if (supportedMethods != null) {
            //设置可以处理的请求方法
            response.setHeader("Allow", StringUtils.arrayToDelimitedString(supportedMethods, ", "));
        }
        response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, ex.getMessage());
        return new ModelAndView();
    }

    protected ModelAndView handleNoHandlerFoundException(NoHandlerFoundException ex,
                                                         HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return new ModelAndView();
    }


    protected void sendServerError(Exception ex, HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        request.setAttribute("javax.servlet.error.exception", ex);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }

}
